package com.lagou.rocketmq.service;

import com.lagou.rocketmq.dao.GoodsQuantityDao;
import com.lagou.rocketmq.dao.OrderDao;
import com.lagou.rocketmq.model.GoodsQuantity;
import com.lagou.rocketmq.model.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @ClassName GoodsQuantityServiceImpl
 * @Description TODO
 * @Author xsq
 * @Date 2020/11/25 15:46
 **/
@Slf4j
@Service
public class GoodsQuantityServiceImpl {

    private final static String QUANTITY = "quantity";

    @Autowired
    private GoodsQuantityDao goodsQuantityDao;
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RedisTemplate redisTemplate;

    public void initGoodsQuantity() {
        if (!redisTemplate.hasKey(QUANTITY)) {
            Optional<GoodsQuantity> count = goodsQuantityDao.findById(1L);
            log.info("初始化订单数量了"+count);
            redisTemplate.opsForValue().set(QUANTITY, count.get().getQuantity());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void addGoods(String id) {
        //减库存
        goodsQuantityDao.updateQuantity();
        //下订单
        Orders orders = new Orders();
        orders.setOrderId(id);
        orders.setOrderStatus(0);
        orderDao.save(orders);
    }
}
